<?php

class DeliveryRequestsController extends AppController {

    var $name = 'DeliveryRequests';
    var $pageTitle = 'Delivery Request';
    var $viewPath = 'customers/delivery/requests';
    var $uses = array('DeRH', 'DeR', 'CustomerSupplier', 'Customer', 'Site', 'RunningNo', 'DeRStatus', 'CustProductSite', 'Supplier', 'User');
    var $paginate = array(
        'DeRH' => array(
            'order' => 'DeRH.request_no DESC'
        )
    );
    var $components = array('Email');

    const DELIVERY_REQUEST_TYPE = 'RQU';

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'delivery_requests');
    }

    function display() {
        parent::display('DeRH');
        $this->paginate['DeRH']['contain'] = array('Supplier', 'DeRStatus', 'DeRtH');

        $this->_checkSite('DeRH');
        $this->_checkBetweenSearch('DeRH', 'request_date');
        $this->_checkBetweenSearch('DeRH', 'due_date');
        $op = array(
            'request_no' => 'LIKE',
            'request_by' => 'LIKE',
            'end_user' => 'LIKE',
            'customer_document_no' => 'LIKE',
        );

        // search โดย received & released
        if (!empty($this->data['DeRH']['delivery_request_status_id']) && $this->data['DeRH']['delivery_request_status_id'] == 99) {
//            $this->paginate['DeRH']['conditions']['DeRH.delivery_request_status_id'] = DeRStatus::RECEIVED;
            $this->data['DeRH']['delivery_request_status_id'] = DeRStatus::RECEIVED;
            $op['delivery_request_status_id'] = '>=';
        }

        $this->_paging('DeRH', $op);
    }

    function save() {
        $is_success = true;
        $id = null;

        $mode = $this->data['mode'];
        if ($mode == 'add' || $mode == 'revise') {

            $is_success = $this->_save_request();
        } elseif ($mode == 'receive') {

            $is_success = $this->_receive_request();
        } elseif ($mode == 'cancel') {
            $this->_cancel_request($this->data['DeRH']['id']);
        } elseif ($mode == 'release') {
            $this->_release_request($this->data['DeRH']['id']);
        }

        // save comment if exists.
        if (!empty($this->data['DeRH']['customer_comment'])) {
            $this->DeRH->id = $this->data['DeRH']['id'];
            $is_success &= $this->DeRH->saveField('customer_comment', $this->data['DeRH']['customer_comment']);
            $is_success &= $this->DeRH->saveField('collector_id', $this->Auth->user('id'));
        }

        if (!empty($this->data['DeRH']['supplier_comment'])) {
            $this->DeRH->id = $this->data['DeRH']['id'];
            $is_success &= $this->DeRH->saveField('supplier_comment', $this->data['DeRH']['supplier_comment']);
        }

        if ($is_success) {
            $id = $this->DeRH->id;
            $this->Session->setFlash("Delivery request save succesfull.", 'flash/ok');
        } else {
            if ($this->data['mode'] == 'revise') {
                $this->passedArgs['revise'] = true;
            }
            $this->Session->setFlash("Delivery request save fail!!!.", 'flash/fail');
        }
        $this->data['DeR'] = null;
        $this->redirect('view/' . $id);
    }

    function _save_request() {
        $cust_request_head_id = null;
        $is_success = true;
        if (!empty($this->data)) {
            $this->DeRH->query("BEGIN");
            $mode = $this->data['mode'];

            if ($mode == 'revise') {
                // ถ้าเป็น mode revise คืน request_qty กลับเข้า supplier_current_stock ให้หมดก่อนแล้วทำการ save ใหม่ตามปกติ
                $this->DeR->contain();
                $deRs = $this->DeR->findAllByDeliveryRequestHeadId($this->data['DeRH']['id']);

                foreach ($deRs as &$data) {

                    // ลด request_qty / เพิ่ม supplier_cs
                    $supplier_cs = $this->CustProductSite->reduceRequestQty($data['DeR']['cust_product_site_id'], $data['DeR']['request_qty']);
                }
            }

            // เรียงลำดับรายการใหม่ กรณีลบแถว Index เปลี่ยน
            $this->adjustRowIndex($this->data['DeR']);

            // ตรวจสอบว่ามีสินค้าอยู่ในใบ
            if (count($this->data['DeR']) == 0) {
                $this->Session->setFlash("Request must have at least one product !!!.", 'flash/fail');
                $is_success = false;
            } else {

                $user_id = $this->Auth->user('id');
                $customer_id = $this->Auth->user('customer_id');
                $site_id = $this->Auth->user('site_id');


                if ($mode == 'add') {

                    // Generate Stock Out No
                    $this->Customer->id = $customer_id;
                    $cust_no = $this->Customer->field('cust_no');
                    $this->Site->id = $site_id;
                    $site_no = $this->Site->field('site_no');
                    $year = $this->Utility->getThaiYear();
                    $runno = $this->RunningNo->getNextStockNo(self::DELIVERY_REQUEST_TYPE, $year, $customer_id);
                    $this->data['DeRH']['request_no'] = $cust_no . '-' . $site_no . '-' . self::DELIVERY_REQUEST_TYPE . '-' . $year . $runno;
                } else { // $mode == 'revise'
                    //update DeRH เก่าว่า ถูก revised
                    $this->DeRH->id = $this->data['DeRH']['id'];
                    $this->DeRH->saveField('delivery_request_status_id', DeRStatus::REVISED);

                    // ลบ id เก่าออก เพิ่ม add ใบใหม่
                    $this->data['DeRH']['id'] = null;
                }

                $this->data['DeRH']['customer_id'] = $customer_id;
                $this->data['DeRH']['site_id'] = $site_id;
                $this->data['DeRH']['user_id'] = $user_id;

                // status เริ่มต้น ON REQUEST
                $this->data['DeRH']['delivery_request_status_id'] = DeRStatus::ON_REQUEST;

                if ($this->DeRH->saveAll($this->data, array('validate' => 'first', 'atomic' => false)) == true) {    // ถ้าไม่ใช่จะ return array error field
                    // update CPS จำนวนที่ถูก request ไว้
                    foreach ($this->data['DeR'] as $dr) {
                        $this->CustProductSite->addRequestQty($dr['cust_product_site_id'], $dr['request_qty']);
                    }
                } else {
                    $is_success = false;
                }
            }

            if ($is_success == true) {
                $this->DeRH->query("COMMIT");
                $this->_sendEmail($this->DeRH->id);
                $this->data['DeRH']['id'] = $this->DeRH->id;
            } else {
                $this->DeRH->query("ROLLBACK");
            }
        } else {
            return false;
        }
        return $is_success;
    }

    function _receive_request() {
        $is_success = true;
//        debug($this->data);
        if (!empty($this->data)) {
            $this->DeRH->query("BEGIN");
            $user_id = $this->Auth->user('id');
            $customer_id = $this->Auth->user('customer_id');
            $site_id = $this->Auth->user('site_id');

            // เปลี่ยน status เป้น receive
            $this->data['DeRH']['delivery_request_status_id'] = DeRStatus::RECEIVED;
            $this->data['DeRH']['receive_date'] = date('Y-m-d');
            if ($this->DeRH->saveAll($this->data, array('validate' => 'first', 'atomic' => false)) == true) {    // ถ้าไม่ใช่จะ return array error field
                // เช็คว่า จำนวน partial หรือไม่
                $is_partial = $this->DeRH->field('is_partial');
                $deRs = $this->DeR->findAllByDeliveryRequestHeadId($this->data['DeRH']['id']);
                $count = count($deRs);
                for ($i = 0; $i < $count; ++$i) {
                    // จำนวนที่ delivery ไม่เท่าจำนวนที่ receive
                    if ($this->data['DeR'][$i]['receive_qty'] != $deRs[$i]['DeR']['delivery_qty']) {

                        // เอาจำนวนที่ไม่ได้ receive กลับเข้าคลัง
                        $qty = $deRs[$i]['DeR']['delivery_qty'] - $deRs[$i]['DeR']['receive_qty'];
                        $this->CustProductSite->id = $this->data['DeR'][$i]['cust_product_site_id'];
                        $supplier_cs = $this->CustProductSite->field('supplier_current_stock');
                        $this->CustProductSite->saveField('supplier_current_stock', $supplier_cs + $qty);

                        $is_partial |= true;
                    }
                }
                $this->DeRH->saveField('is_partial', $is_partial);
            } else {
                $is_success = false;
            }

            if ($is_success == true) {
                $this->DeRH->query("COMMIT");
            } else {
                $this->DeRH->query("ROLLBACK");
            }
        } else {
            $this->passedArgs['receive'] = true;
            return false;
        }
        return $is_success;
    }

    function _cancel_request($id) {
        $this->DeRH->id = $id;
        $is_success = $this->DeRH->saveField('delivery_request_status_id', DeRStatus::CANCEL);
        $is_success &= $this->DeRH->saveField('cancel_date', date('Y-m-d'));

        $this->DeR->contain();
        $data = $this->DeR->findAllByDeliveryRequestHeadId($id);
        // cancel ปรับ request qty กลับไปเพิ่ม current_stock
        foreach ($data as $dr) {
            $this->CustProductSite->id = $dr['DeR']['cust_product_site_id'];
            // ลด request_qty ที่ CPS
            $request_qty = $this->CustProductSite->field('request_qty');
            $this->CustProductSite->saveField('request_qty', $request_qty - $dr['DeR']['request_qty']);

            // เพิ่ม supplier_current_stock
            $supplier_cs = $this->CustProductSite->field('supplier_current_stock');
            $this->CustProductSite->saveField('supplier_current_stock', $supplier_cs + $dr['DeR']['request_qty']);
        }
    }

    function _release_request($id) {
        $this->DeRH->id = $id;
        $is_success = $this->DeRH->saveField('delivery_request_status_id', DeRStatus::RELEASED);
        $is_success &= $this->DeRH->saveField('release_date', date('Y-m-d'));
    }

    /**
     * ส่ง Email แจ้ง ITS admin กับ ผู้ดูลแต่ละ customer ว่ามีการ Stock out แล้ว
     * @param <type> $id
     */
    function _sendEmail($id) {
        $customer_id = $this->Auth->user('customer_id');
        $userName = $this->Auth->user('name');
        $this->Customer->id = $customer_id;
        $customerName = $this->Customer->field('name');
        $this->Site->id = $this->Auth->user('site_id');
        $siteName = $this->Site->field('name');
        $this->DeRH->id = $id;
        $supplier_id = $this->DeRH->field('supplier_id');

        // ส่ง e-mail กลับหา admin และ ผู้ดูแลแต่ละ customer (ถ้ามี)
        $emailsTo = array();
        $emailsTo[] = $this->requestAction('system_preferences/get/contact_email');
        $response_email = $this->Customer->field('response_email');
        if (!empty($response_email)) {
            $emailsTo[] = $response_email;
        }

        $coh_emails = $this->User->listEmailUserSupplierByCustomer($customer_id, $supplier_id);
        foreach ($coh_emails as $email) {
            $emailsTo[] = $email;
        }

        $this->Supplier->id = $this->DeRH->field('supplier_id');
        $emailsTo[] = $this->Supplier->field('email');

        $this->set('userName', $userName);
        $this->set('customerName', $customerName);
        $this->set('siteName', $siteName);
        $this->set('id', $id);

        $emailFrom = "{$userName} {$customerName} {$siteName} <{$this->Auth->user('email')}>";
        $subject = 'VMI : Customer Delivery Request ' . $this->DeRH->field('request_no');
        $template = 'customer/request';

        $this->sendEmails($emailFrom, $emailsTo, $subject, $template);
    }

    function view($id = null) {
        if ($id != null) {
            $this->DeRH->contain(array('Supplier', 'DeRStatus', 'DeRtH', 'DeR' => array('Product' => array('Unit'), 'CustProductSite')));
            $this->data = $this->DeRH->findById($id);

            $this->_neighbors($id, $this->DeRH, array('fields' => array('id', 'request_no')));
            $status_id = $this->data['DeRH']['delivery_request_status_id'];

            // On Request ลูกค้าสามารถทำการ revise ได้
            if (isset($this->passedArgs['revise'])) {
                // generate revise no.
                $request_no = $this->data['DeRH']['request_no'];

                // Revise ครั้งแรก
                if (strlen($request_no) <= 23) {
                    $this->data['DeRH']['request_no'] = $request_no . ' Rev. 1';
                } else {
                    // ดึงหมายเลข revision no จาก request no
                    $revise_no = (int) substr($request_no, 28) + 1;
                    $this->data['DeRH']['request_no'] = substr($request_no, 0, 22) . ' Rev. ' . $revise_no;
                }

                $this->set('mode', 'revise');
            } elseif (isset($this->passedArgs['receive'])) {
                // On Delivery ลูกค้าจะทำการ receive
                $this->set('mode', 'receive');
            } elseif (isset($this->passedArgs['release'])) {
                $this->set('mode', 'release');
                $this->DeRStatus->id = DeRStatus::RELEASED;
                $this->data['DeRStatus']['title'] = $this->DeRStatus->field('title');
            } elseif (isset($this->passedArgs['cancel'])) {
                // On Delivery ลูกค้าจะทำการ cancel
                $this->set('mode', 'cancel');
                $this->DeRStatus->id = DeRStatus::CANCEL;
                $this->data['DeRStatus']['title'] = $this->DeRStatus->field('title');
            } else {
                $this->set('mode', 'edit');
            }
        } else { // mode add
            $status_id = DeRStatus::ON_REQUEST;
            $this->set('suppliers', $this->CustomerSupplier->listSupplierByCustomerId($this->Auth->user('customer_id')));  // กำหนดผู้ทำการ stock out
            $this->set('request_by', $this->Auth->user('name'));  // กำหนดผู้ทำการ stock out
            $this->set('today', date("d/m/Y"));                 // กำหนด default วันที่ stock out
            $this->set('mode', 'add');
        }
        $this->set('customer_id', $this->Auth->user('customer_id'));
        $this->set('site_id', $this->Auth->user('site_id'));
        $this->set('status_id', $status_id);
    }

    /**
     * ใช้หน้าเดียวกับ SupplierDeliveryRequest
     */
    function print_view($id) {
        $this->redirect('/supplier_delivery_requests/print_view/' . $id);
    }

    function popup_search() {
        parent::popup_search();
        $statuses = $this->DeRStatus->find('list');
        $statuses[99] = 'Received & Released';
        $this->set('statuses', $statuses);
        $this->set('suppliers', $this->CustomerSupplier->listSupplierByCustomerId($this->Auth->user('customer_id')));  // กำหนดผู้ทำการ stock out
        $this->set('popupWidth', 500);
    }

    /**
     * นับจำนวน Delivery Request ที่มี status เป็น On REQUEST
     */
    function get_on_request_count() {
        return $this->DeRH->find('count', array(
            'conditions' => array(
                'DeRH.customer_id' => $this->Auth->user('customer_id'),
                'DeRH.site_id' => $this->Auth->user('site_id'),
                'delivery_request_status_id' => DeRStatus::ON_REQUEST
            )
        ));
    }

}

?>